import React, { useEffect, useState } from 'react';
import { history, connect } from 'umi';
import { Card, Avatar, Divider, Descriptions, Space, Typography, Button, Popover, Row, Col, Checkbox, Form } from 'antd';
import Schedu from './components/Schedu';
import moment from 'moment';
import FixButton from '@/components/FlxButton'
import './index.less'

const BatchScheduling = (props) => {
    const { history = {}, dispatch } = props
    const { location = {} } = history
    const { query = {} } = location
    const { id, } = query
    const [teacherOnlineList, setTeachOnlineList] = useState([])
    const [teacherOfflineList, setTeacherOfflineList] = useState([])
    const [recruitmentOnline, setRecruitmentOnline] = useState([])
    const [recruitmentOfflineList, setRecruitmentOfflineList] = useState([])
    const [subjectList, setSubjectList] = useState([])
    const [subjectOfflineList, setSubjectOfflineList] = useState([])
    const [selectedRowList, setSelectRowList] = useState(['teacherOnline', 'teacherOffline',])
    const [defaultScheduleList, setDefaultList] = useState([])
    const [initStatus, setInitStatus] = useState(false)
    const [form1] = Form.useForm();
    const [form2] = Form.useForm();
    const [form3] = Form.useForm();
    const [form4] = Form.useForm();
    const [form5] = Form.useForm();
    const [form6] = Form.useForm();
    const fetchData = () => {
        dispatch({
            type: 'answering/fetchListSchedule',
            callback: (vals) => {
                setDefaultList(vals)
                const defaut = vals
                dispatch({
                    type: 'answering/fetchListTeacherSchedule',
                    payload: {
                        teacherId: id,
                        qaTypes: 'teacherOnline,teacherOffline,recruitmentOnline,recruitmentOffline,subject',
                        page: 1,
                        limit: 9999
                    },
                    callback: (e = []) => {
                        const teacherOnline = []
                        const teacherOffline = []
                        const recruitmentOnline = []
                        const recruitmentOffline = []
                        const subject = []
                        const newList = e.map(val => {
                            let { teachingMode, weekDays, startDate, endDate, campusId, classroomId, fullAddress, scheduleTimes = '', teacherIds, excludeDates = '', id } = val
                            scheduleTimes = scheduleTimes.length > 0 ? JSON.parse(scheduleTimes) : []
                            const schedList = scheduleTimes.reduce((o, vals,) => {
                                const { scheduleType } = vals
                                if (scheduleType === 'schedule') {
                                    return [...o, vals]
                                }
                                else {
                                    return o
                                }
                            }, [])
                            const scheduleTimesList = scheduleTimes.reduce((o, vals,) => {
                                const { scheduleType, startTime, endTime, maxStudentAmount } = vals
                                if (scheduleType !== 'schedule') {
                                    return [...o, {
                                        maxStudentAmount,
                                        dateTime: [moment(startTime, 'HH:mm'), moment(endTime, 'HH:mm')]
                                    }]
                                }
                                else {
                                    return o
                                }
                            }, [])
                            const data = defaut.reduce((item, vals, index) => {
                                const database = {}
                                schedList.forEach(c => {
                                    if (c.scheduleId === vals.id) {
                                        database['schedule' + index] = true
                                        database['scheduleCount' + index] = c.maxStudentAmount
                                    }
                                })
                                return {
                                    ...item, ...database
                                }
                            }, {})
                            return {
                                dateTime: [moment(startDate, 'YYYY-MM-DD'), moment(endDate, 'YYYY-MM-DD')],
                                campusId,
                                classroomId,
                                teacherIds,
                                excludeDates: excludeDates.length > 0 ? excludeDates.split(',') : [],
                                weekDays: weekDays.length > 0 ? weekDays.split(',') : '',
                                id,
                                ...data,
                                scheduleTimes: scheduleTimesList,
                                fullAddress,
                                teachingMode
                            }
                        })
                        newList.forEach(val => {
                            if (val.teachingMode === 'teacherOnline') {
                                teacherOnline.push(val)
                            }
                            else if (val.teachingMode === 'teacherOffline') {
                                teacherOffline.push(val)
                            }
                            else if (val.teachingMode === 'recruitmentOnline') {
                                recruitmentOnline.push(val)
                            }
                            else if (val.teachingMode === 'recruitmentOffline') {
                                recruitmentOffline.push(val)
                            }
                            else if (val.teachingMode === 'subject') {
                                subject.push(val)
                            }
                        })
                        setInitStatus(() => {
                            setTeachOnlineList(teacherOnline.length > 0 ? teacherOnline : [{}])
                            setTeacherOfflineList(teacherOffline.length > 0 ? teacherOffline : [{}])
                            setRecruitmentOnline(recruitmentOnline.length > 0 ? recruitmentOnline : [{}])
                            setRecruitmentOfflineList(recruitmentOffline.length > 0 ? recruitmentOffline : [{}])
                            setSubjectList(subject.length > 0 ? subject : [{}])
                            return true
                        })
                    }
                })
            }
        })

    }
    useEffect(() => {
        fetchData()
    }, [])

    const qaTypeList = [{
        value: 'teacherOnline',
        label: '找老师在线',

    }, {
        value: 'teacherOffline',
        label: '找老师线下',

    }, {
        value: 'recruitmentOnline',
        label: '招考在线',

    }, {
        value: 'recruitmentOffline',
        label: '招考线下',

    },
    {
        value: 'subject',
        label: '学科答疑',

    },
    ]

    const submit = async () => {
        const formList = []
        if (selectedRowList.includes('teacherOnline')) {
            formList.push(form1.validateFields)
        }
        if (selectedRowList.includes('teacherOffline')) {
            formList.push(form2.validateFields)
        }
        if (selectedRowList.includes('recruitmentOnline')) {
            formList.push(form3.validateFields)
        }
        if (selectedRowList.includes('recruitmentOffline')) {
            formList.push(form4.validateFields)
        }
        if (selectedRowList.includes('subject')) {
            formList.push(form5.validateFields)
        }
        Promise.all(formList.map(item => { return item() })).then(val => {
            const typeList = val.map(item => {
                const { teachingMode, teacherScheduleList = [] } = item
                const list = teacherScheduleList.map(item => {
                    const {
                        dateTime,
                        scheduleTimes = [],
                        weekDays = [],
                        id,
                        excludeDates = [],
                        campusId,
                        classroomId
                    } = item
                    const schedList = defaultScheduleList.reduce((o, val, index) => {
                        const { id, startTime, endTime } = val
                        if (item['schedule' + index]) {
                            return [...o, {
                                scheduleType: 'schedule',
                                scheduleId: id,
                                maxStudentAmount: item['scheduleCount' + index],
                                startTime,
                                endTime
                            }]
                        }
                        return o
                    }, [])
                    const payload = {
                        teachingMode,
                        weekDays: weekDays.toString(),
                        startDate: moment(dateTime[0]).format('YYYY-MM-DD'),
                        endDate: moment(dateTime[1]).format('YYYY-MM-DD'),
                        campusId,
                        classroomId,
                        scheduleTimes: [...scheduleTimes.map(item => {
                            const { dateTime, maxStudentAmount } = item
                            return {
                                startTime: dateTime[0].format('HH:mm'),
                                endTime: dateTime[1].format('HH:mm'),
                                maxStudentAmount,
                                scheduleType: 'self'
                            }
                        }), ...schedList],
                        teacherIds: query.id,
                        excludeDates: excludeDates.toString(),
                        id
                    }

                    return payload
                })
                return list
            })
            const payloadList = typeList.reduce((item, index) => {
                return [...item, ...index]
            })
            dispatch({
                type: 'answering/fakeSaveTeacherScheduleConfig',
                payload: {
                    teacherScheduleList: payloadList
                },
                callback: (e) => {
                    history.goBack();
                }
            })
        })
    }
    return <Card
        title='批量排班'
        extra={<Button type='link' onClick={() => { history.goBack() }}>返回列表</Button>}
    >
        <Row gutter={[24, 24]}>
            <Col span={24}>
                <Checkbox.Group onChange={(e) => {
                    setSelectRowList(e)
                }} value={selectedRowList} options={qaTypeList}>

                </Checkbox.Group>
            </Col>
            {initStatus && <div>
                {selectedRowList.includes('teacherOnline') && <Col span={24}>
                    <Space style={{ width: '60%' }} direction='vertical'>
                        <div style={{ fontSize: 16, fontWeight: 'bold' }}>找老师在线</div>
                        <Schedu offlineStatus={0} form={form1} detail={{ teacherScheduleList: teacherOnlineList, teachingMode: 'teacherOnline' }}></Schedu>
                    </Space>
                </Col>}
                {selectedRowList.includes('teacherOffline') && <Col span={24}>
                    <Space style={{ width: '60%' }} direction='vertical'>
                        <div style={{ fontSize: 16, fontWeight: 'bold' }}>找老师线下</div>
                        <Schedu offlineStatus={1} form={form2} detail={{ teacherScheduleList: teacherOfflineList, teachingMode: 'teacherOffline' }}></Schedu>
                    </Space>
                </Col>}
                {selectedRowList.includes('recruitmentOnline') && <Col span={24}>
                    <Space style={{ width: '60%' }} direction='vertical'>
                        <div style={{ fontSize: 16, fontWeight: 'bold' }}>招考在线</div>
                        <Schedu offlineStatus={0} form={form3} detail={{ teacherScheduleList: recruitmentOnline, teachingMode: 'recruitmentOnline' }}></Schedu>
                    </Space>
                </Col>}
                {selectedRowList.includes('recruitmentOffline') && <Col span={24}>
                    <Space style={{ width: '60%' }} direction='vertical'>
                        <div style={{ fontSize: 16, fontWeight: 'bold' }}>招考线下</div>
                        <Schedu offlineStatus={1} form={form4} detail={{ teacherScheduleList: recruitmentOfflineList, teachingMode: 'recruitmentOffline' }}></Schedu>
                    </Space>
                </Col>}

                {selectedRowList.includes('subject') && <Col span={24}>
                    <Space style={{ width: '60%' }} direction='vertical'>
                        <div style={{ fontSize: 16, fontWeight: 'bold' }}>学科答疑</div>
                        <Schedu offlineStatus={0} form={form5} detail={{ teacherScheduleList: subjectList, teachingMode: 'subject' }}></Schedu>
                    </Space>
                </Col>}
            </div>}

            <FixButton onOk={() => { submit() }}></FixButton>
        </Row>
    </Card >
}
export default connect(({ subscriber, loading }) => ({
    loading: loading.effects['subscriber/fetchUserDetail'],
}))(BatchScheduling);